package com.iuie.ns.datum.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;


public class WindowsCommand {

	public volatile static WindowsCommand command = null;
	
	private Socket socket;
	
	private PrintWriter writer;
	
	private WindowsCommand() {
	}
	
	private void connect() {
		try {
			this.socket = new Socket("127.0.0.1", 8888);
			this.writer = new PrintWriter(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static WindowsCommand getWindowsCommand() {  
	    if (command == null) {  
	        synchronized (WindowsCommand.class) {  
		        if (command == null) {
		        	command = new WindowsCommand();
		        }  
		    }  
		    return command;
	    }
	    return command;
	}
	
	public void execute(String command) {
		if (this.socket == null) {
			this.connect();
		}
		try {
			this.socket.sendUrgentData(0xff);
		} catch (IOException e) {
			e.printStackTrace();
			this.disconnect();
		}
		
		this.writer.println(command);
		this.writer.flush();
	}
	
	private void disconnect() {
		if (this.socket != null) {
			try {
				this.socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (this.writer != null) {
			this.writer.close();
		}
		this.socket = null;
		this.writer = null;
	}
	
	public static void main(String[] args) {
		WindowsCommand.getWindowsCommand().execute("openfolder?D:\\Program Files\\apache-tomcat-7.0.56\\data\\files\\");
	}
	

}
